package com.dempsey.springboot06securityjwtredis.framework.security.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.dempsey.springboot06securityjwtredis.framework.entity.LoginUser;
import com.dempsey.springboot06securityjwtredis.project.entity.User;
import com.dempsey.springboot06securityjwtredis.project.mapper.UserMapper;
import com.dempsey.springboot06securityjwtredis.project.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 用户验证处理
 */
@Service
public class CustomUserDetailsService implements UserDetailsService {

    @Autowired
    private UserService userService;

    @Autowired
    private UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("name", username);
        User user = userService.getOne(queryWrapper);

        return createLoginUser(user);
    }

    public UserDetails createLoginUser(User user) {
        int userId = user.getId();
        List<String> userRoles = userMapper.getUserRoles(userId);
        return new LoginUser(user, userRoles);
    }
}
